﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Practices.Prism.Interactivity.InteractionRequest;

namespace Okazuki.MVVM.PrismSupport.Interactivity
{
    public class MessageBoxTriggerAction : DispatcherTriggerAction
    {
        private static readonly MessageBoxConfirmation NullObject = new MessageBoxConfirmation();
        private static readonly Notification NullNotification = new Notification();

        public static readonly DependencyProperty MessageBoxButtonProperty =
            DependencyProperty.Register(
                "MessageBoxButton",
                typeof(MessageBoxButton),
                typeof(MessageBoxTriggerAction),
                new PropertyMetadata(MessageBoxButton.OK));

        public static readonly DependencyProperty MessageBoxTextProperty =
            DependencyProperty.Register(
                "MessageBoxText",
                typeof(string),
                typeof(MessageBoxTriggerAction),
                new PropertyMetadata(null));

        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register(
                "Title",
                typeof(string),
                typeof(MessageBoxTriggerAction),
                new PropertyMetadata(null));

        public MessageBoxButton MessageBoxButton
        {
            get { return (MessageBoxButton)GetValue(MessageBoxButtonProperty); }
            set { SetValue(MessageBoxButtonProperty, value); }
        }

        public string MessageBoxText
        {
            get { return (string)GetValue(MessageBoxTextProperty); }
            set { SetValue(MessageBoxTextProperty, value); }
        }

        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }

        protected override void InvokeAction(InteractionRequestedEventArgs e)
        {
            var notification = e.Context ?? NullNotification;
            var confirmation = e.Context as MessageBoxConfirmation ?? NullObject;
            var ret = MessageBox.Show(
                notification.GetMessage() ?? this.MessageBoxText,
                notification.Title ?? this.Title,
                confirmation.MessageBoxButton ?? this.MessageBoxButton);
            if (confirmation != NullObject)
            {
                confirmation.Confirmed = ret == MessageBoxResult.OK || ret == MessageBoxResult.Yes;
            }
            e.Callback();
        }
    }
}
